package com.example.pclimb.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.pclimb.R;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.auth.ChangePasswordActivity;
import com.example.pclimb.ui.auth.EditProfileActivity;
import com.example.pclimb.ui.auth.LoginActivity;
import com.example.pclimb.ui.guide.ApplyGuideActivity;
import com.example.pclimb.ui.admin.AdminPanelActivity;
import com.example.pclimb.util.SharedPreferencesUtil;
import com.example.pclimb.viewmodel.UserViewModel;

import de.hdodenhof.circleimageview.CircleImageView;

public class MeFragment extends Fragment {

    private static final String TAG = "MeFragment";
    private CircleImageView imgAvatar;
    private TextView tvUsername;
    private TextView tvUserType;
    private TextView tvPhone;
    private LinearLayout llApplyGuide;
    private LinearLayout llChangePassword;
    private LinearLayout llLogout;
    private LinearLayout llAdminPanel;
    private CardView cardAdminPanel;
    private UserViewModel userViewModel;
    private User currentUser;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_me, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 初始化视图
        initViews(view);

        // 初始化ViewModel
        userViewModel = new ViewModelProvider(requireActivity()).get(UserViewModel.class);

        // 绑定点击事件
        bindClickEvents();

        // 观察用户数据变化
        observeUserData();
    }

    private void initViews(View view) {
        imgAvatar = view.findViewById(R.id.img_avatar);
        tvUsername = view.findViewById(R.id.tv_username);
        tvUserType = view.findViewById(R.id.tv_user_type);
        tvPhone = view.findViewById(R.id.tv_phone);
        llApplyGuide = view.findViewById(R.id.ll_apply_guide);
        llChangePassword = view.findViewById(R.id.ll_change_password);
        llLogout = view.findViewById(R.id.ll_logout);
        llAdminPanel = view.findViewById(R.id.ll_admin_panel);
        cardAdminPanel = view.findViewById(R.id.card_admin_panel);
        view.findViewById(R.id.btn_edit_profile).setOnClickListener(v -> 
            startActivity(new Intent(requireActivity(), EditProfileActivity.class)));
    }

    private void bindClickEvents() {
        // 申请成为陪爬向导
        llApplyGuide.setOnClickListener(v -> {
            if (currentUser != null) {
                if (currentUser.getUserType() == User.TYPE_GUIDE) {
                    Toast.makeText(requireContext(), "您已经是陪爬向导了", Toast.LENGTH_SHORT).show();
                } else {
                    startActivity(new Intent(requireActivity(), ApplyGuideActivity.class));
                }
            }
        });

        // 修改密码
        llChangePassword.setOnClickListener(v ->
            startActivity(new Intent(requireActivity(), ChangePasswordActivity.class)));

        // 管理员面板
        llAdminPanel.setOnClickListener(v -> {
            startActivity(new Intent(requireActivity(), AdminPanelActivity.class));
        });

        // 退出登录
        llLogout.setOnClickListener(v -> logout());
    }

    private void observeUserData() {
        // 从SharedPreferences获取用户信息
        int userId = SharedPreferencesUtil.getUserId(requireContext());
        Log.d(TAG, "获取用户信息，用户ID: " + userId);
        
        if (userId != -1) {
            userViewModel.getUserById(userId).observe(getViewLifecycleOwner(), user -> {
                if (user != null) {
                    Log.d(TAG, "成功获取用户信息: " + user.getUsername());
                    currentUser = user;
                    updateUI(user);
                }
            });
        }
    }

    private void updateUI(User user) {
        // 更新用户信息UI
        tvUsername.setText(user.getUsername());
        
        // 设置用户类型显示
        String userTypeText;
        if (user.isGuide() || user.getUserType() == User.TYPE_GUIDE) {
            userTypeText = "陪爬向导";
            llApplyGuide.setVisibility(View.GONE); // 已是向导，隐藏申请按钮
        } else if (user.isAdmin() || user.getUserType() == User.TYPE_ADMIN) {
            userTypeText = "管理员";
            llApplyGuide.setVisibility(View.GONE); // 管理员，隐藏申请按钮
            cardAdminPanel.setVisibility(View.VISIBLE); // 管理员，显示管理员面板入口
        } else if (user.isGuideApplied()) {
            userTypeText = "申请审核中";
            llApplyGuide.setVisibility(View.GONE); // 已申请，隐藏申请按钮
        } else {
            userTypeText = "普通用户";
            llApplyGuide.setVisibility(View.VISIBLE); // 普通用户，显示申请按钮
        }
        tvUserType.setText(userTypeText);
        
        // 设置手机号码，如果有的话
        String phoneNumber = user.getPhone() != null ? user.getPhone() : user.getPhoneNumber();
        if (phoneNumber != null && !phoneNumber.isEmpty()) {
            tvPhone.setText(phoneNumber);
        } else {
            tvPhone.setText("未设置手机号");
        }
    }

    private void logout() {
        // 清除登录信息
        SharedPreferencesUtil.clearUserInfo(requireContext());
        
        // 跳转到登录页面
        Intent intent = new Intent(requireActivity(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        requireActivity().finish();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 页面恢复时更新用户信息
        observeUserData();
    }
} 